<template lang="">
    <div class="warp">
         <el-form :inline="true" :model="formInfo" class="box" :rules="rules" ref="ruleFormRef" >
         <h2>登录</h2>
    <el-form-item label="用户名" prop="username">
      <el-input  v-model="formInfo.username"   placeholder="请输入用户名" />
    </el-form-item>
   <div>
     <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="formInfo.password"   placeholder="请输入密码" />
    </el-form-item>
   </div>
     <div>
    <el-form-item>
    <el-button type="primary" @click="login(ruleFormRef)">登录</el-button>
    </el-form-item>
    </div>
  </el-form>
    </div>
</template>
<script lang="ts" setup>
import { getuserlogin } from '../request/api'
import { reactive, ref } from 'vue';
// 引入路由的方法
import { useRouter } from "vue-router";
// 引入数据类型规则
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import store from '@/store';

// 引入路由的控制器
const router = useRouter();
console.log(router, '路由控制器');

// 创建一个ref
const ruleFormRef = ref<FormInstance>()

const formInfo = ref({
  username: '',
  password: '',
})
// 定义规则
const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 8, message: '用户名长度2到8', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 10, message: '密码长度3到10', trigger: 'blur' },
  ],
})

//定义登录事件
//  element-plus 2.0以上的版本 规则验证是 异步操作
//规则验证
const login = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(formInfo, "表单对象");
      console.log("准备登录!");
      //调用登录接口
      getuserlogin(formInfo.value).then((res: any) => {
        console.log(res, '登录');
        if (res.code == 200) {
          ElMessage.success(res.msg)
          // 把登录信息存储到vuex中
          store.dispatch('changeUserAction', res.list)
          //跳转
          router.push('/index')
        } else {
          ElMessage.error(res.msg)
        }
      })

    } else {
      console.log("验证失败", fields);
    }
  });
};
</script>
<style scoped>
.warp {
  width: 100%;
  height: 95vh;
  background: linear-gradient(rgb(71 114 193), rgb(209 33 195));
}

.box {
  text-align: center;
  width: 400px;
  height: 276px;
  border-radius: 10px;
  background-color: #fff;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  padding: 20px 0px 0px 0px;
  box-sizing: border-box;


}
</style>